// rootUrl
window.rootUrl = '';
// useSSL
window.useSSL = false;
// http port
window.httpPort = 80;
// https port
window.httpPort = 443;
// websocket port
window.wsPort = 23850;

// 获取url中的参数
window.getUrlParam = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var search = decodeURIComponent(window.location.search);
    if (search[0] === '?')
        search = search.substr(1);
    var r = search.match(reg);  //匹配目标参数
    return (r != null) ? unescape(r[2]) : null;
};

// 在head中添加脚本
window.appendScript = function(url){
    var script = document.createElement('script');
    script.async = false;
    script.src = url;
    document.head.appendChild(script);
};

// 发送请求（重新链接，非ajax）
window.sendRequest = function(url, action, params, target){
    var form = document.createElement("form");
    form.action = url;
    form.method = action;
    if (target)
        form.target = target;
    params = params || {};

    try{
        params = JSON.parse(JSON.stringify(params));
    }catch(e){
        showMessage('post param invalid');
        return;
    }

    for (var key in params){
        if (key !== undefined){
            input = document.createElement("input");
            input.type = "hidden";
            input.name = key;
            input.value = params[key];
            form.appendChild(input)
        }
    }
    try{
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
    }catch(e){
        showMessage('post request error');
        return;
    }
};

// 以POST方式发送请求（重新链接，非ajax）
window.postRequest = function(url, params, target){
    window.sendRequest(url, 'POST', params, target);
};

/**
 * 截取带HTML样式的字符串，并保留并自动补齐HTML标签
 * html  将要截取的HTML字符串
 * len   大致长度，会根据该长度截取字符串，去掉尾部错误标签，然后补全标签
 */
window.subHtml = function(html, len){
    if (html.length > len)
        html = html.substr(0, len);
    let pos = html.search(/<[^>]$/);
    if (pos > 0)
        html.substr(0, pos);
    let d = document.createElement('div');
    d.innerHTML = html;
    return d.innerHTML;
};

window.handleCKEditorData = function(html){
    let d = document.createElement('div');
    d.innerHTML = html;
    if (d.childNodes.length > 1){
        var node = d.childNodes[d.childNodes.length-2];
        if ((typeof(node.innerHTML) === 'string' && node.innerHTML.length > 1024) || node.nodeName === '#text'){
            d.removeChild(node);
        }
    }
    if (d.childNodes.length > 0){
        var node = d.childNodes[d.childNodes.length-1];
        if ((typeof(node.innerHTML) === 'string' && node.innerHTML.length > 1024) || node.nodeName === '#text'){
            d.removeChild(node);
        }
    }
    return d.innerHTML;
};

window.getText = function(html){
    let d = document.createElement('div');
    d.innerHTML = html;
    return d.innerText.replace(/[\r\n\t]/g, '');
};

window.sharePage = function(node, type){
    let thisTitle = document.title;
    let thisUrl = window.location.href;
    switch (type){
        case 'sina' : window.open('http://v.t.sina.com.cn/share/share.php?title='+encodeURIComponent(thisTitle)+'&url='+encodeURIComponent(thisUrl));break;
        case 'qqblog' : window.open('http://v.t.qq.com/share/share.php?title='+encodeURIComponent(thisTitle)+'&url='+encodeURIComponent(thisUrl));break;
        case 'qqzone' : window.open('http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?title='+encodeURIComponent(thisTitle)+'&url='+encodeURIComponent(thisUrl));break;
        case 'renren' : window.open('http://***/share/buttonshare?title='+encodeURIComponent(thisTitle)+'&link='+encodeURIComponent(thisUrl));break;
        case 'kaixin' : window.open('http://www.kaixin001.com/repaste/share.php?rtitle='+encodeURIComponent(thisTitle)+'&rurl='+encodeURIComponent(thisUrl));break;
        case 'weixin' :
            var imgDiv = document.createElement('div');
            let left = node.offsetLeft - 78 - 12;
            left = left > 0 ? left : 0;
            let top = node.offsetTop - 156 - 117 - 12;
            top = top > 0 ? top : 0;

            imgDiv.innerHTML = '<div class="padding-arround" style="position:absolute;text-align:center;left:'+left+'px;top:'+top+'px;background-color:gainsboro">' +
                '<img src="http://qr.topscan.com/api.php?text='+window.location.href+'" style="width:156px"/>'+
                '<a href="javascript:;" style="font-size:22px;padding:6px;color:black;text-decoration:none;position:absolute;top:0;right:0" onclick="document.body.removeChild(this.parentNode.parentNode)">×</a>'+
                '<p style="font-size:12px">或复制以下链接发送给好友</p><textarea rows="3" cols="23" style="font-size:9px" onfocus="this.select()">'+window.location.href+'</textarea>' +
                '</div>';
            document.body.appendChild(imgDiv);
            break;
    }
};

window.createSocket = function(){
    return io.connect("ws://"+window.location.hostname+":4000");
};

window.setCookie = function(name, value, timeout){
    //设置名称为name,值为value的Cookie
    var expdate = new Date();   //初始化时间
    expdate.setTime(expdate.getTime() + timeout);   //时间
    document.cookie = name+"="+value+";expires="+expdate.toGMTString()+";path=/";
    //即document.cookie= name+"="+value+";path=/";   时间可以不要，但路径(path)必须要填写，因为JS的默认路径是当前页，如果不填，此cookie只在当前页面生效！~
};

window.getCookie = function(name) {
    if (document.cookie.length > 0) {
        let c_start = document.cookie.indexOf(name + "=");
        if (c_start !== -1) {
            c_start = c_start + name.length + 1;
            let c_end = document.cookie.indexOf(";", c_start);
            if (c_end === -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
};
window.saveFormValues = function(jqnode){
    let vals = [];
    jqnode.find('input').each(function(){
        if ($(this).prop('checked')){
            vals.push(true);
        } else{
            let val =$(this).prop('value');
            if (val === '' && $(this).attr('value') === undefined)
                vals.push(null);
            else
                vals.push(val);
        }
    });
    jqnode.find('textarea').each(function(){vals.push($(this).prop('value'))});
    jqnode.find('select').each(function(){vals.push($(this).prop('value'))});
    return vals;
};
window.loadFormValues = function(jqnode, vals){
    if (!vals instanceof Array)
        return false;
    jqnode.find('input').each(function(){
        try {
            let val = vals.shift();
            $(this).prop('checked', val === true);
            if (val === null)
                $(this).removeAttr('value');
            else
                $(this).prop('value', val);
        } catch(err) {
        }
    });
    jqnode.find('textarea').each(function(){$(this).prop('value', vals.shift())});
    jqnode.find('select').each(function(){$(this).prop('value', vals.shift())});
    return true;
};


document.onreadystatechange = function(){
    if (document.readyState !== 'complete')
        return;
    let sesschilds = document.querySelectorAll('alljs-widget>*');
    for (let node of sesschilds) {
        let txt = node.innerText;
        if (txt.match(/^<%.*%>$/))
            continue;
        window[node.localName] = node.innerText;
        if (node.localName === 'message-top' || node.localName === 'message-bottom'){
            if (txt)
                node.style.setProperty('display', 'block');
        }
    }

    let imgs = document.querySelectorAll('.article-content img');
    for (let idx=0;idx<imgs.length;idx++){
        imgs[idx].onclick = function(){
            let d = document.createElement('div');
            d.setAttribute('class', 'article-img-div');
            d.innerHTML='<div></div>'+imgs[idx].outerHTML+'<div></div>';
            d.onclick = function(){this.remove();};
            document.body.appendChild(d);
        }
    }

    if (!('fetch' in window && 'assign' in Object)){
        window.appendScript(window.rootUrl + '/node_modules/babel-polyfill/dist/polyfill.min.js');
    }
    if ('_cordovaNative' in window){
        window.appendScript(window.rootUrl + '/android/cordova.js');
        window.appendScript(window.rootUrl + '/res/device.js');
    } else {
        window.appendScript(window.rootUrl + '/res/browser.js');
    }
};

window.showMessage = function(msg){
    let node = document.querySelector('alljs-widget>message-top');
    if (node){
        node.innerText = msg;
        node.style.setProperty('display', 'none');
        node.style.setProperty('animation', '');
        node.style.setProperty('-webkit-animation', '');
        setTimeout(function(){
            node.style.setProperty('animation', 'fade-out 4s forwards');
            node.style.setProperty('-webkit-animation', 'fade-out 4s forwards');
            node.style.setProperty('display', 'block');
        }, 50);
    }
};

window.browser = {
    versions : (function() {
        var u = navigator.userAgent;
        return {//移动终端浏览器版本信息
            trident : u.indexOf('Trident') > -1, //IE内核
            presto : u.indexOf('Presto') > -1, //opera内核
            webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, //火狐内核
            mobile : !!u.match(/AppleWebKit.*Mobile.*/)
                || !!u.match(/AppleWebKit/), //是否为移动终端
            ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp : u.indexOf('Safari') === -1,
            //是否web应该程序，没有头部与底部
            google:u.indexOf('Chrome')>-1
        };
    })(),
    language : (navigator.browserLanguage || navigator.language).toLowerCase()
};
window.system = (function(){
    var p = navigator.platform;
    return {//平台、设备和操作系统
        win: p.indexOf("Win") === 0,
        mac: p.indexOf("Mac") === 0,
        xll: (p === "X11") || (p.indexOf("Linux") === 0),
        ipad:!!navigator.userAgent.match(/iPad/i)
    };
})();

